/**
 * 
 */
package com.thon.controller.rest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.thon.alipay.util.AlipayNotify;
import com.thon.commons.config.Global;
import com.thon.entity.user.FundDetail;
import com.thon.entity.user.User;
import com.thon.service.user.FundDetailService;
import com.thon.service.user.UserService;

/**
 * @author thon
 * @date Jan 22, 2014 3:05:38 PM
 */
@Controller
@RequestMapping(value = "/api/alipay")
public class AlipayRestController {
	private static final String ALIPAY_NOTIFY_URL = "https://mapi.alipay.com/gateway.do?service=%s&partner=%s&notify_id=%s";
	private static final String ALIPAY_STATUS_SUCCCESS = "success";
	private static final String ALIPAY_STATUS_FAIL = "fail";
	private static final Log log = LogFactory.getLog(AlipayRestController.class);
	@Autowired
	private FundDetailService fundDetailService;
	@Autowired
	private UserService userService;
	// 快捷支付回调接口
	@RequestMapping(value="/shortcut/async",method = RequestMethod.POST)
	@ResponseBody
	public String shortcutAsync(HttpServletRequest request){
		log.info("------------shortcut start-------------");
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			System.out.println(">>>>>>>>>");
			System.out.print(name);
			System.out.print(valueStr);
			System.out.println("<<<<<<<<<");
			params.put(name, valueStr);
		}
		
		String notifyData = params.get("notify_data");
		Document doc = Jsoup.parse(notifyData);
		String tradeNo = doc.select("out_trade_no").first().text();
		String tradeStatus = doc.select("trade_status").first().text();
		
		// TODO 安全验证
		System.out.println(">>>>>验证成功");
		if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
			FundDetail fundDetail = new FundDetail();
			fundDetail = fundDetailService.getFundDetail(tradeNo);
			fundDetail.setActionType(1);
			fundDetailService.updateFundDetail(fundDetail);
			User user = new User();
			user = userService.getUser(fundDetail.getUser().getId());
			user.setFund(user.getFund() + fundDetail.getAmount());
			userService.updateUser(user);
			//System.out.println(">>>>>充值成功" + tradeNo);
		}
		log.info("------------shortcut end-------------");
		return ALIPAY_STATUS_SUCCCESS;
	}
	
	// 普通支付回调接口
	@RequestMapping(value = "/async",method = RequestMethod.POST, produces = "text/html")
	@ResponseBody
	public String async(HttpServletRequest request, HttpServletResponse response){
		
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
//			System.out.println(">>>>>>>>>");
//			System.out.print(name+":");
//			System.out.print(valueStr);
//			System.out.println("<<<<<<<<<");
			params.put(name, valueStr);
		}

		String tradeNo = request.getParameter("out_trade_no");
		String tradeStatus = request.getParameter("trade_status");
		
		
		try {
			if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
				FundDetail fundDetail = new FundDetail();
				fundDetail = fundDetailService.getFundDetail(tradeNo);
				if (fundDetail.getActionType() == 3) {
					fundDetail.setActionType(1);
					fundDetailService.updateFundDetail(fundDetail);
					User user = new User();
					user = userService.getUser(fundDetail.getUser().getId());
					user.setFund(user.getFund() + fundDetail.getAmount());
					userService.updateUser(user);
					log.info( "success" + "," + tradeNo + "," + tradeStatus + "," + user.getId() + "," + fundDetail.getAmount());
				}
			}
			
			log.info( "success" + "," + tradeNo + "," + tradeStatus);
			return ALIPAY_STATUS_SUCCCESS;
		} catch (Exception e) {
			log.error( "error:" + "," + tradeNo + "," + tradeStatus + "," + e.getLocalizedMessage());
			return ALIPAY_STATUS_FAIL;
		}
		
	}
	@RequestMapping(value = "/return_url",method = RequestMethod.GET)
	public String rechangeReturn(HttpServletRequest request,Model model){
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]: valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		String tradeNo = request.getParameter("out_trade_no");
		String tradeStatus = request.getParameter("trade_status");
		//String notifyId = request.getParameter("notify_id");
		if(tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
			model.addAttribute("result", "success");
		}else{//验证失败
			model.addAttribute("result", "fail");
		}
		return "return_url";
	}
}
